package com.infore.dataReceiving.controller;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.infore.dataReceiving.constant.Constants;
import com.infore.dataReceiving.core.enums.Water2018InstructionsTypeEnum;
import com.infore.dataReceiving.dto.WaterInstructionsDataDto;
import com.infore.dataReceiving.entity.BackControlLog;
import com.infore.dataReceiving.enums.ResultStatus;
import com.infore.dataReceiving.repository.IBackControlLogRepository;
import com.infore.dataReceiving.util.CRCCheck;
import com.infore.dataReceiving.util.Water2018InstructionsHandleUtil;
import com.infore.dataReceiving.util.Page;
import com.infore.dataReceiving.util.ResultEntity;
import io.netty.channel.ChannelHandlerContext;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Controller
public class Water2018BackControlInstructionController {
	
	@Autowired
	private IBackControlLogRepository iBackControlLogRepository;
	
	@ApiOperation(value = "发送反控指令", notes = "发送反控指令")
    @ApiImplicitParams({@ApiImplicitParam(name = "mn", value = "站点mn号", paramType = "query", required = true, dataType = "String"),
    	    @ApiImplicitParam(name = "password", value = "站点密码", paramType = "query", required = true, dataType = "String"),
    	    @ApiImplicitParam(name = "projectCode", value = "因子编号", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cn", value = "指令编号", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "condition", value = "其他条件，逗号分隔", paramType = "query", required = true, dataType = "String")
    })
	@RequestMapping(value = "/sendBackControl", method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity sendBackControl(String mn,String password,String projectCode,String cn,String condition) throws Exception {
		ChannelHandlerContext ctx = Water2018InstructionsHandleUtil.cMap.get("water_"+mn);
		if(ctx==null) {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("设备不在线，请稍后再试！"); 
		}
		if(mn==null||"".equals(mn)) {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("站点MN不允许为空!");
		}
		if(password==null||"".equals(password)) {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("站点密码不允许为空!");
		}
//		if(projectCode==null||"".equals(projectCode)) {
//			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("分析仪不允许为空!");
//		}
		if(cn==null||"".equals(cn)) {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("指令编号不允许为空!");
		}
		SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		Date date = new Date();
		String qn = sdfDateFormat.format(date);
		if(Water2018InstructionsTypeEnum.water2018_3085.getCn().equals(cn)) {//空白校准
			String dataArea = "PolId="+projectCode;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3085.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3086.getCn().equals(cn)) {//标样校准
			String dataArea = "PolId="+projectCode;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3086.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3083.getCn().equals(cn)) {//零点核查
			String dataArea = "PolId="+projectCode;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3083.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3084.getCn().equals(cn)) {//跨度核查
			String dataArea = "PolId="+projectCode;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3084.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_1014.getCn().equals(cn)) {//提取数采仪时间
			String dataArea = "";
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_1014.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_1015.getCn().equals(cn)) {//数采仪校时
			String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String dataArea = "SystemTime="+time;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_1015.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3020.getCn().equals(cn)&&"log".equals(condition.split(",")[0])) {//提取仪表日志
			String dataArea = "PolId="+projectCode+",InfoId=i11001;BeginTime="+condition.split(",")[1]+";EndTime="+condition.split(",")[2];
			send(qn,cn,password,mn,"提取监测仪表日志",projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3020.getCn().equals(cn)&&"param".equals(condition.split(",")[0])) {//提取仪表参数
			String dataArea = "PolId="+projectCode+",InfoId="+condition.split(",")[1];
			send(qn,cn,password,mn,"提取监测仪表参数",projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3020.getCn().equals(cn)&&"state".equals(condition.split(",")[0])) {//提取仪表状态
			String dataArea = "PolId="+projectCode+",InfoId="+condition.split(",")[1];
			send(qn,cn,password,mn,"提取监测仪表状态",projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_1011.getCn().equals(cn)) {//提取监测仪表时间
			String dataArea = "PolId="+projectCode;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_1011.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_1012.getCn().equals(cn)) {//设置监测仪表时间
			String dataArea = "PolId="+projectCode+";SystemTime=20160801085857";
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_1012.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3043.getCn().equals(cn)) {//远程重启现场数采仪
			String dataArea = "";
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3043.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3046.getCn().equals(cn)) {//远程控制系统进入待机命令
			String dataArea = "PolId=w00000";
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3046.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3044.getCn().equals(cn)) {//远程启动系统单次测试
			String dataArea = "";
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3044.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3042.getCn().equals(cn)) {//远程切换运行模式
			String dataArea = "RunMode="+condition;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3042.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_1072.getCn().equals(cn)) {//设置数采仪密码
			String dataArea = "NewPW="+condition;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_1072.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3056.getCn().equals(cn)) {//远程设置系统运行测量时间间隔
			String dataArea = "RunInterval="+condition;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3056.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_1061.getCn().equals(cn)) {//提取实时数据间隔
			String dataArea = "";
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_1061.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_1062.getCn().equals(cn)) {//设置实时数据间隔
			String dataArea = "RtdInterval="+condition;
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_1062.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_1000.getCn().equals(cn)) {//设置超时时间及重发次数
			String[] strArr = condition.split(",");
			String dataArea = "OverTime="+strArr[0]+";ReCount="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_1000.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3081.getCn().equals(cn)) {//启动单台仪表加标回收
			String[] strArr = condition.split(",");
			String dataArea = "PolId="+strArr[0]+";Volume="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3081.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_2011.getCn().equals(cn)) {//提取监测指标实时数据
			String[] strArr = condition.split(",");
			String dataArea = "BeginTime="+strArr[0]+";EndTime="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_2011.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_2061.getCn().equals(cn)) {//提取监测指标小时数据
			String[] strArr = condition.split(",");
			String dataArea = "BeginTime="+strArr[0]+";EndTime="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_2061.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_2062.getCn().equals(cn)) {//提取监测指标核查数据
			String[] strArr = condition.split(",");
			String dataArea = "BeginTime="+strArr[0]+";EndTime="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_2062.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_2063.getCn().equals(cn)) {//提取监测指标加标回收数据
			String[] strArr = condition.split(",");
			String dataArea = "BeginTime="+strArr[0]+";EndTime="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_2063.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_2064.getCn().equals(cn)) {//提取监测指标平行样测试数据
			String[] strArr = condition.split(",");
			String dataArea = "BeginTime="+strArr[0]+";EndTime="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_2064.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_2065.getCn().equals(cn)) {//提取监测指标零点核查数据
			String[] strArr = condition.split(",");
			String dataArea = "BeginTime="+strArr[0]+";EndTime="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_2065.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_2066.getCn().equals(cn)) {//提取监测指标跨度核查数据
			String[] strArr = condition.split(",");
			String dataArea = "BeginTime="+strArr[0]+";EndTime="+strArr[1];
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_2066.getMsg(),projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3020.getCn().equals(cn)&&"jcstate".equals(condition.split(",")[0])) {//提取数采仪状态
			String dataArea = "InfoId="+condition.split(",")[1];
			send(qn,cn,password,mn,"提取数采仪状态",projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3020.getCn().equals(cn)&&"jclog".equals(condition.split(",")[0])) {//提取数采仪日志
			String dataArea = "InfoId=i21001;BeginTime="+condition.split(",")[1]+";EndTime="+condition.split(",")[2];
			send(qn,cn,password,mn,"提取数采仪日志",projectCode,date,ctx,dataArea);
		}else if(Water2018InstructionsTypeEnum.water2018_3015.getCn().equals(cn)) {//手动远程留样
			String dataArea = "";
			send(qn,cn,password,mn,Water2018InstructionsTypeEnum.water2018_3015.getMsg(),projectCode,date,ctx,dataArea);
		}else {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.DEAL_SUCCESS).setInfo("暂时不支持该指令,请联系管理员添加!");
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.DEAL_SUCCESS).setInfo("指令发送成功,请查看日志确认反控结果!");
	}
	
	
	@ApiOperation(value = "查看反控日志", notes = "查看反控日志")
    @ApiImplicitParams({@ApiImplicitParam(name = "mn", value = "站点mn号", paramType = "query", required = true, dataType = "String"),
    	    @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", required = true, dataType = "String"),
    	    @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", required = true, dataType = "String"),
    	    @ApiImplicitParam(name = "pageNum", value = "第几页", paramType = "query", required = true, dataType = "String"),
        	@ApiImplicitParam(name = "pageSize", value = "每页多少条记录", paramType = "query", required = true, dataType = "String")
    })
	@RequestMapping(value = "/queryBackControlLog", method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity queryBackControlLog(String mn,String startTime,String endTime,String pageNum,String pageSize) throws Exception {
		int a = Integer.valueOf(pageNum)-1;
		int b = Integer.valueOf(pageSize);
		int startSize = a*b+1;
		int endSize = Integer.valueOf(pageNum)*b;
		List<BackControlLog> logList = iBackControlLogRepository.queryBackControlLog(mn, startTime+" 00:00:00", endTime+" 23:59:59",endSize,startSize);
		
		int count = iBackControlLogRepository.findBackControlLogCount(mn, startTime+" 00:00:00", endTime+" 23:59:59");
		int yu = count/Integer.valueOf(pageSize);
		int mo = count%Integer.valueOf(pageSize);
		if(mo>0) {
			yu+=1;
		}
		Page<BackControlLog> page = new Page<BackControlLog>();
		page.setList(logList);
		page.setPageNo(Integer.valueOf(pageNum));
		page.setPageSize(Integer.valueOf(pageSize));
		page.setTotalPages(yu);
		page.setTotalRecords(count);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.DEAL_SUCCESS).setPage(page);
	}
	
	
	public void send(String qn,String cn,String password,String mn,String description,
			String projectCode,Date date,ChannelHandlerContext ctx,String dataArea) {
		String datas = "QN="+qn+";ST=21;CN="+cn+";PW="+password+";MN="+mn+";Flag=9;CP=&&"+dataArea+"&&";
		int dataLength = datas.length();//数据段长度
		String crc = CRCCheck.crc16(datas, dataLength);
		String dataLengthString = Water2018InstructionsHandleUtil.getDataLengthString(dataLength+"");
		String returnInfo = "##"+dataLengthString+datas+crc+"\r\n";
		ctx.channel().writeAndFlush(returnInfo);
		
		BackControlLog log = new BackControlLog();
		log.setQn(qn);
		log.setMn(mn);
		log.setProjectCode(projectCode);
		log.setCn(cn);
		log.setDescription(description);
		log.setOperationUser("admin");
		log.setOperationTime(new Timestamp(date.getTime()));
		log.setIp("127.0.0.1");
		log.setContent(returnInfo);
		iBackControlLogRepository.save(log);
	}
	
	

}
